package fm

import (
	"fmt"
	"gitee.com/xluomo945/fm/setting"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"time"
)

var (
	defaultConn        *gorm.DB
	defaultMaxIdleConn = 10
	defaultMaxOpenConn = 50
	defaultMaxLifeTime = time.Hour
	connUser           string
	connPass           string
	connHost           string
	connPort           string
	connName           string
)

func (app *App) openDatabase() error {
	// 如果没有设置连接配置不连接不报错直接结束
	if app.ConfigurationConfig.DatabaseConnConfig.Conn == nil {
		log.Println("[Warn] database config not setting")
		return nil
	}

	buildDatabaseConnConfig(app.ConfigurationConfig.DatabaseConnConfig)

	// 连接数据库 默认按mysql连接
	db, err := app.buildMysqlConn()
	if err != nil {
		return err
	}

	// 设置连接池的相关设置
	sqlDb, err := db.DB()
	if err != nil {
		return err
	}
	sqlDb.SetMaxIdleConns(defaultMaxIdleConn)
	sqlDb.SetMaxOpenConns(defaultMaxOpenConn)
	sqlDb.SetConnMaxLifetime(defaultMaxLifeTime)

	// 连接的db存起来
	defaultConn = db
	return nil
}

func (app *App) buildMysqlConn() (*gorm.DB, error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", connUser, connPass, connHost, connPort, connName)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		return nil, fmt.Errorf("[Fail] database conn is invalid. conn config is [%s:******(len:%d)@tcp(%s:%s)]. conn error is :%s", connUser, len(connPass), connHost, connPort, err.Error())
	}
	return db, nil
}

func buildDatabaseConnConfig(config setting.DatabaseConfig) {
	connUser = config.Conn.GetUser()
	connPass = config.Conn.GetPass()
	connHost = config.Conn.GetHost()
	connPort = config.Conn.GetPort()
	connName = config.Conn.GetDbName()

	if config.Pool != nil {
		defaultMaxIdleConn = config.Pool.GetMaxIdleCount()
		defaultMaxOpenConn = config.Pool.GetMaxOpenCount()
		defaultMaxLifeTime = config.Pool.GetMaxLifeTime()
	}
}

func DB() *gorm.DB {
	return defaultConn
}
